package com.lottery.pay.Utils.wxUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;

public class MultiUtil {
	/**
	 * Convert hex string to byte[]
	 * 
	 * @param hexString
	 *            the hex string
	 * @return byte[]
	 */
	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	/**
	 * Convert char to byte
	 * 
	 * @param c
	 *            char
	 * @return byte
	 */
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	public static String getByteString(byte[] buff_out) {
		StringBuffer strBuf = new StringBuffer(buff_out.length * 3);
		strBuf.append("Length[");
		strBuf.append(buff_out.length);
		strBuf.append("];Content[");
		for (int i = 0; i < buff_out.length; ++i) {
			int l = buff_out[i] & 0x0F;
			int h = (buff_out[i] & 0xF0) >> 4;

			char ll = (char) (l > 9 ? 'a' + l - 10 : '0' + l);
			char hh = (char) (h > 9 ? 'a' + h - 10 : '0' + h);

			strBuf.append(hh);
			strBuf.append(ll);
			strBuf.append(" ");
		}
		strBuf.append("]");
		return strBuf.toString().toUpperCase();
	}

	public static String getBasePathByClass(Class<?> classz) {
		String cfgBasePath = "";
		try {
			String path = classz.getProtectionDomain().getCodeSource()
					.getLocation().getFile();
			path = URLDecoder.decode(path, "UTF-8");
			File file = new File(path);
			path = file.getAbsolutePath();
			if (path.endsWith(".jar")) {
				path = file.getParent();
			}
			String className = classz.getCanonicalName();
			className = className.replace(".", File.separator);
			if (path.contains(className)) {
				path = path.substring(0, path.indexOf(className) - 1);
			}
			cfgBasePath = path;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return cfgBasePath;
	}
	
	
	public static String filterOffUtf8Mb4(String text) throws UnsupportedEncodingException {
		byte[] bytes = text.getBytes("UTF-8");
		ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
		int i = 0;
		while (i < bytes.length) {
			short b = bytes[i];
			if (b > 0) {
				buffer.put(bytes[i++]);
				continue;
			}
			b += 256;
			if ((b ^ 0xC0) >> 4 == 0) {
				buffer.put(bytes, i, 2);
				i += 2;
			}
			else if ((b ^ 0xE0) >> 4 == 0) {
				buffer.put(bytes, i, 3);
				i += 3;
			}
			else if ((b ^ 0xF0) >> 4 == 0) {
				i += 4;
			}
		}
		//add by jpzhang.for utf8mb4字符问题
		byte[] dest=new byte[buffer.position()];
        buffer.flip();
        System.arraycopy(buffer.array(), 0, dest, 0, dest.length);
		return new String(dest, "utf-8");
	}
}
